package com.qys.training.biz.auth.service.impl;

import com.qys.training.base.enumerate.BizCodeEnum;
import com.qys.training.base.exception.QysException;
import com.qys.training.biz.auth.entity.User;
import com.qys.training.biz.auth.mapper.UserMapper;
import com.qys.training.biz.auth.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    public Long create(User user) {
        //查询用户名是否重复
        String username = userMapper.checkUsername(user.getUsername());
        if (!StringUtils.isEmpty(username)) {
            throw new QysException(BizCodeEnum.USER_EXISTED.getCode(), BizCodeEnum.USER_EXISTED.getDescription());
        }
        //密码 MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);
        return user.getId();
    }

    @Override
    public User proving(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return userMapper.proving(user);
    }

    public void testQysException() {
        throw new QysException(BizCodeEnum.ERROR.getCode(), BizCodeEnum.ERROR.getDescription());
    }

    public void testOtherException() {
        int error = 10 / 0;
    }
}
